<template>
  <div class="main">
    <p class="main_p1">Products</p>
    <p style="color: gray; margin: 20px auto 8px auto">Search</p>
    <el-input v-model="searchValue" style="width: 220px; margin-bottom: 20px" />

    <ElTable
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{
        color: 'black',
        padding: '10px',
        'border-bottom': 'solid 2px #DCDFE6',
      }"
      :cell-style="cellStyle"
      v-loading="loading"
    >
      <ElTableColumn prop="name" label="Name" :align="'left'" />
      <ElTableColumn prop="type" label="Type" :align="'left'" />
      <ElTableColumn :align="'center'">
        <template #default="scope">
          <RouterLink
            :to="{ name: 'ProductPage', params: { id: scope.row.id } }"
            >See more!
          </RouterLink>
        </template>
      </ElTableColumn>
    </ElTable>
  </div>
</template>

<script setup lang="ts">
import { getAllProducts, isProductAbstractArray } from '@/api/products';
import { promiseRef } from '@/utils/promiseRef';
import { ElMessage, ElTable, ElTableColumn } from 'element-plus';
import { computed, ref } from 'vue';
const searchValue = ref('');
const loading = ref(true);
const allData = promiseRef(
  (async () => {
    const res = await getAllProducts();
    const data = res.data;
    if (!isProductAbstractArray(data)) {
      ElMessage.error('data is not a product array');
      throw new Error('data is not a product array');
    }
    loading.value = false;
    return data;
  })(),
  []
);
const tableData = computed(() => {
  if (searchValue.value == '') {
    return allData.value;
  } else {
    const key = searchValue.value.toLocaleLowerCase();
    return allData.value.filter(item => {
      return (
        item.name.toLowerCase().includes(key) ||
        item.type.toLowerCase().includes(key)
      );
    });
  }
});
function cellStyle({ rowIndex }: { rowIndex: number }) {
  if (!(rowIndex % 2)) {
    return {
      padding: '10px',
      background: '#F2F6FC',
      'border-bottom': 'solid 2px #E4E7ED',
    };
  } else {
    return {
      padding: '10px',
      background: 'white',
      'border-bottom': 'solid 2px #E4E7ED',
    };
  }
}
</script>

<style scoped>
@import '../assets/style.css';

a {
  text-decoration: none;
}

.router-link-active {
  text-decoration: none;
}
</style>
